#pragma once
#include <iostream>
using namespace std;
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "myLog.hpp"
#include "Err.hpp"

const static int gbacklog = 32;
const static int default_sock = -1;
class Sock
{
public:
    Sock():_sock(default_sock)
    {
    }

    void Socket()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            logMessge(FATAL, "创建套接字失败！错误码：%d ,错误原因：%s ", errno, strerror(errno));
            exit(SOCK_ERR);
        }
        logMessge(DEBUG, "创建套接字成功");
    }
    void Bind(uint16_t Port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_addr.s_addr = INADDR_ANY;
        peer.sin_family = AF_INET;
        peer.sin_port = htons(Port);
        if (bind(_sock, (struct sockaddr *)&peer, sizeof(peer)) < 0)
        {
            logMessge(FATAL, "绑定失败！错误码：%d ,错误原因：%s ", errno, strerror(errno));
            exit(BIND_ERR);
        }
        logMessge(DEBUG, "绑定成功！");
    }
    void Listen()
    {
        if (listen(_sock, gbacklog) < 0)
        {
            logMessge(FATAL, "监听失败！错误码：%d ,错误原因：%s ", errno, strerror(errno));
        }
        logMessge(DEBUG, "监听成功！");
    }
    int Accept(string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in temp;
        socklen_t len=sizeof(temp);
        memset(&temp, 0, sizeof(temp));

        int sock = accept(_sock, (struct sockaddr *)&temp, &len);

        if (sock < 0)
        {
            logMessge(WARING, "连接失败！错误码：%d 错误原因：%s", errno, strerror(errno));
        }
        else
        {
            *clientip = inet_ntoa(temp.sin_addr);
            *clientport = ntohs(temp.sin_port);
        }
        return sock;
    }
    ~Sock()
    {
    }
    int Fd()
    {
        return _sock;
    }

private:
    int _sock;
};